package com.example.demo.algorithm;

/**
 * TODO:最长公共前缀
 *
 * @date:2021/10/14 10:51
 * @author:Vicky(陈烟星)
 */
public class ArrayTest1 {

    /**
     * TODO:
     *  编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，则返回""
     *  输入: ["flower","flow","flight"]
     * 输出: "fl"
     * <p>
     * 输入: ["dog","racecar","car"]
     * 输出: ""
     *
     * @param args
     */
    public static void main(String[] args) {
        String[] strs = new String[]{"flower", "flow", "flight"};
        if (strs.length == 0) {
            System.out.println("");
        }
        String base = strs[0];
        while (base.length() > 0) {
            boolean check = true;
            for (String item : strs) {
                int indexOf = item.indexOf(base);
                if (indexOf != 0) {
                    check = false;
                }
            }
            if (check) {
                break;
            }
            if (base.length() != 1) {
                base = base.substring(0, base.length() - 1);
            } else {
                base = "";
                break;
            }
        }
        System.out.println(base);
    }

}
